<template>
 <div class="inventory-summary-container">
    <el-row>
        <el-col :span="15">
            <div class="title">盘点单信息</div>
        </el-col>
        <el-col :span="8" class="right-align">
            <el-button type="danger" @click="submitCheckResults">结束盘点</el-button>
        </el-col>
    </el-row>
    <el-row :gutter="20">
        <el-col :span="8">
            <div class="info-box">
                <div class="info-header">盘点单号:</div>
                <div class="info-content">{{ orderDetail.orderCode || '' }}</div>
            </div>
        </el-col>
        <el-col :span="8">
            <div class="info-box">
                <div class="info-header">盘点单名称</div>
               
                <div class="info-content">{{ fatherQuery.orderName || '' }}</div>
            </div>
        </el-col>
    </el-row>
    <el-row :gutter="20">
        <el-col :span="8">
            <div class="info-box">
                <div class="info-header">当前库存数量</div>
                <div class="info-content">{{ orderDetail.totalNum }}</div>
            </div>
        </el-col>
        <el-col :span="8">
            <div class="info-box">
                <div class="info-header">当前盘点进度</div>
                <div class="info-content">已盘点{{ currentCheckedNum }}种 / 共{{ currentCheckedSum }}个</div>
            </div>
        </el-col>
        <el-col :span="8">
            <div class="info-box">
                <div class="info-header">当前未盘点数</div>
                <div class="info-content">{{ unCheckedNum }}种 / 共{{ unCheckedSum }}个</div>
            </div>
        </el-col>
    </el-row>
    <el-row :gutter="20">
        <el-col :span="8">
            <div class="info-box">
                <div class="info-header">当前库存总成本</div>
                <div class="info-content">{{ orderDetail.totalPrice? orderDetail.totalPrice.toFixed(2) : '' }}</div>
            </div>
        </el-col>
        <el-col :span="8">
            <div class="info-box">
                <div class="info-header">当前盘点总成本</div>
                <div class="info-content">{{ currentCheckedCost? currentCheckedCost.toFixed(2) : '' }}</div>
            </div>
        </el-col>
        <el-col :span="8">
            <div class="info-box">
                <div class="info-header">当前未盘点总成本</div>
                <div class="info-content">{{ unCheckedCost? unCheckedCost.toFixed(2) : '' }}</div>
            </div>
        </el-col>
    </el-row>
</div>
<div class="button-container-first">
            <el-button :type="currentView === 'start'? 'primary' : 'plain'" @click="changeView('start')" :disabled="isReadonly">进行盘点</el-button>
            <el-button :type="currentView === 'result'? 'primary' : 'plain'" @click="changeView('result')">盘点结果</el-button>
        </div>

  <div v-show="currentView === 'result'" class="button-container-second">
    <el-button v-if="isReadonly" type="primary" @click="jumpAuditOrder">库存调整</el-button>
    <el-button type="primary" @click="">导出列表</el-button>
  </div>

  <div class="content-container">
    <div v-if="currentView === 'start'" class="start-container">
      <!-- 进行盘点的内容 -->
       <el-row >
        <el-col :span="8">
          <el-select v-model="confirmationType" placeholder="请选择">
            <el-option label="手动确认" value="manual"></el-option>
            <el-option label="自动确认" value="automatic"></el-option>
          </el-select>
        </el-col>
        <el-col  :span="9">
          <el-input v-model="searchQuery" placeholder="请输入条码"></el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="searchItem">搜索</el-button>
        </el-col>
       </el-row>
      
      <div class="search-result">
        <el-image
          :src="foundItem.imageUrl || ''"
          fit="cover"
          class="image"
          :preview-src-list="[foundItem.imageUrl || '']"
          style="width: 150px; height: 150px;"
        >
          <template #error>
            <div class="image-slot">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
        <div class="inventory-info">
          <div><strong>货品条码:</strong> {{ foundItem.barcode || '' }}</div>
          <div><strong>成本价:</strong> {{ foundItem.costPrice || '' }}</div>
          <div><strong>标价:</strong> {{ foundItem.tagPrice || '' }}</div>
          <div><strong>市场价:</strong> {{ foundItem.marketPrice || '' }}</div>
          <div><strong>总数量:</strong> {{ foundItem.totalNums || '' }}</div>
          <div>
            <strong>已盘数量:</strong> 
            <el-input v-model.number="foundItem.newCheckNum" style="width: 100px;" />
            <el-button type="primary" @click="saveCheckNum(foundItem, foundItem.newCheckNum)">保存</el-button>
          </div>
          <div><strong>仓库/仓位:</strong> {{ foundItem.warehouseName ? foundItem.warehouseName + '/' : '' }}{{ foundItem.storageName || '' }}</div>
        </div>
      </div>
    </div>
    <div v-if="currentView === 'result'">
      <!-- 盘点结果的内容 -->
      <div class="inventory-result">
        <el-row :gutter="40" v-for="(item, index) in paginatedInventoryData()" :key="index">
          <el-col v-for="(subItem, subIndex) in item" :key="subIndex" :span="6">
            <div class="inventory-item">
              <el-image
                :src="subItem.imageUrl"
                fit="cover"
                class="image"
                :preview-src-list="[subItem.imageUrl]"
                style="width: 100%; height: 150px;"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="inventory-info">
                <div><strong>名称:</strong> {{ subItem.name }}</div>
                <div><strong>条码:</strong> {{ subItem.barcode }}</div>
                <div><strong>总数量:</strong> {{ subItem.totalNums }}</div>
                <div><strong>过去已盘数量:</strong> {{ subItem.countNums }}</div>
                <div><strong>现在已盘数量:</strong> {{ subItem.checkNum||0 }}</div>
                <div><strong>成本价:</strong> {{ subItem.costPrice }}</div>
                <div><strong>标价:</strong> {{ subItem.tagPrice }}</div>
                <div><strong>市场价:</strong> {{ subItem.marketPrice }}</div>
                <div><strong>仓库:</strong> {{ subItem.warehouseName }}</div>
                <div><strong>仓位:</strong> {{ subItem.storageName }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, ref } from "vue";
import '@/mock/inbound.js'
import { onMounted, onBeforeMount } from "vue";
import { ElMessage } from "element-plus";
import { getcheckOrderJade, getcheckOrderDetail, resultCheckOrder } from '@/api/inbound/inbound'
import { useRoute, useRouter } from "vue-router"
import { useStore } from 'vuex';
export default defineComponent({
  name: "StartCheck",
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const fatherQuery = reactive({});
    const inventoryData = ref([]); // 存储盘点所有翡翠数据
    const currentView = ref("start");
    const confirmationType = ref('manual');
    const searchQuery = ref('');
    const orderDetail = reactive({
     orderCode: '',
     totalNum: 0,
     totalPrice: 0, // 设置一个合理的默认值，避免初始为 null
     curNum: 0,
     curPrice: 0.0,
     newCheckNum: null,
   });

    //全是相关计算
    const currentCheckedNum = ref(0);
    const currentCheckedSum = ref(0);
    const unCheckedNum = ref(0);
    const unCheckedSum = ref(0);
    const currentCheckedCost = ref(0);
    const unCheckedCost = ref(0);

    const foundItem = reactive({
      name: null,
      barcode: null,
      totalNums: null,
      countNums: null,
      costPrice: null,
      tagPrice: null,
      marketPrice: null,
      imageId: null,
      warehouseId: null,
      warehouseName: null,
      storageId: null,
      storageName: null,
      imageUrl: null,
    });
    const isReadonly = ref(false);// 用来决定相关几个按钮在盘点单不同状态的显示

    const changeView = (view) => {
      currentView.value = view;
    }

    const toggleReadonly = (value) => {
      isReadonly.value = value;
      if (isReadonly.value) {
        changeView("result");
      }
    }
    
    // 将数据分页，每页显示最多10条（两行，每行5个）
    const paginatedInventoryData = () => {
      const pageSize = 10;
      const totalPages = Math.ceil(inventoryData.value.length / pageSize);
      const result = [];
      for (let i = 0; i < totalPages; i++) {
        result.push(inventoryData.value.slice(i * pageSize, (i + 1) * pageSize));
      }
      return result;
    }

    const searchItem = () => {
      const target = inventoryData.value.find(item => item.barcode === searchQuery.value) || null;
      if(target){
        Object.assign(foundItem, target);
      }else{
        ElMessage.error('未找到匹配的条码');
      }
    }


    // 修改已盘数量并保存到数据中
    const saveCheckNum = (item, newCheckNum) => {
      const previousCheckNum = item.checkNum || 0;
      const difference = newCheckNum - previousCheckNum;
      item.checkNum = newCheckNum;
      // 相关翡翠的数据直接修改
      const found = inventoryData.value.find(invItem => invItem.barcode === item.barcode);
      if (found) {
        found.checkNum = item.checkNum;
        ElMessage.success('已盘数量已保存');
      }

      if (previousCheckNum === 0 && newCheckNum > 0) {
        currentCheckedNum.value++;
        unCheckedNum.value--;
      } else if (previousCheckNum > 0 && newCheckNum === 0) {
        currentCheckedNum.value--;
        unCheckedNum.value++;
      }

      currentCheckedSum.value += difference;
      unCheckedSum.value -= difference;
      currentCheckedCost.value += difference * item.costPrice;
      unCheckedCost.value -= difference * item.costPrice;
    }

    // 提交盘点结果
    const submitCheckResults = () => {
  const checkOrderId = fatherQuery.id;
  const checkJadeList = inventoryData.value.map(item => ({
    barcode: item.barcode,
    checkNum: item.checkNum || item.countNums,
    warehouseId: item.warehouseId,
    storageId: item.storageId,
  }));

  const resultData = {
    checkOrderId,
    checkJadeList,
  };
  console.log("resultData:", resultData);
  resultCheckOrder(resultData).then((res) => {
    if (res.code === 200) {
      ElMessage.success('盘点结果已提交');
      // 使用 window.history.back() 返回上一个页面
      setTimeout(() => {
        window.history.back();
      }, 1000);
    } else {
      ElMessage.error('提交盘点结果失败');
    }
  });
};
    const handleGetCheckOrderList = async (query) => {//获取盘点单列表
      const params = {
        checkOrderId: query.id,
      }
      console.log("params:",params)
      getcheckOrderJade(params).then((res) => {
        console.log("getcheckOrder:",res)
        unCheckedNum.value = res.total
        if (res.rows && res.rows.length) {
          inventoryData.value = res.rows
        } else {
          inventoryData.value = []
        }
      })
      const res = await getcheckOrderDetail({ checkOrderId: route.query.id });
      if (res.code === 200) {
        Object.assign(orderDetail, res.data);
        console.log("orderDetail:",orderDetail)
        // 初始化未盘点的总成本和未盘点数
        unCheckedSum.value = orderDetail.totalNum;
        unCheckedCost.value = orderDetail.totalPrice;
      }
    }

    const jumpAuditOrder = () => {
      router.push({ path: '/inbound/audits' });
    }

    onBeforeMount(() => {
      // Mocking setting isReadonly to true for demonstration purposes.
      // Replace this with actual logic.
      
    });

    onMounted(() => {
      // 外部路由跳转进来时获取传入的相关参数
      Object.assign(fatherQuery, route.query);
      console.log('Route query:', route.query);
      // 假设从创建盘点单成功后跳转过来带有特定参数，如 'canEdit'
      if (route.query && route.query.canEdit) {
        toggleReadonly(false);
        changeView('start');
      } else if (route.query.status === "0") {
        toggleReadonly(false);
      } else {
        toggleReadonly(true);
      }
      console.log("fatherQuery:", fatherQuery);
      handleGetCheckOrderList(fatherQuery);

      // 判断如果是从创建页面跳转过来且带有特定标识，则进入进行盘点页面
      if (route.query && route.query.fromCreate && route.query.fromCreate === 'continueCheck') {
        changeView('start');
      } else {
        // 默认情况或其他情况进入查看明细页面
        changeView('result');
      }
    });


    return {
      fatherQuery,
      currentView,
      changeView,
      isReadonly,
      handleGetCheckOrderList,
      paginatedInventoryData,
      inventoryData,
      confirmationType,
      searchQuery,
      searchItem,
      foundItem,
      orderDetail,
      saveCheckNum,
      submitCheckResults,
      currentCheckedNum,
      currentCheckedSum,
      unCheckedNum,
      unCheckedSum,
      currentCheckedCost,
      unCheckedCost,
      jumpAuditOrder,
    };
  },
});
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.inventory-summary-container {
  background-color: #fff; /* 白色背景板 */
  padding: 20px;
  margin-bottom: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  text-align: left;
}
.right-align {
  display: flex;
  justify-content: flex-end;
}

.info-box {
  display: flex;
  margin-bottom: 10px;
}

.info-header {
  font-weight: bold;
  flex: 0 0 auto; /* 禁止标签伸缩 */
  margin-right: 10px;
}

.info-content {
  flex: 1; /* 值部分占据剩余空间 */
  text-align: left;
}

.button-container-first {
  background-color: #fff; /* 白色背景板 */
  padding: 20px;
  margin-bottom: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  display: flex;
  justify-content: flex-start; /* 左对齐 */
}

.button-container-second {
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #e6e8ee; /* 添加边框 */
  margin-bottom: 5px;
  display: flex;
  justify-content: flex-start; /* 左对齐 */
}

.content-container {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}

.inventory-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  text-align: center;
  margin-bottom: 20px;
}

.inventory-info {
  margin: 10px;
  text-align: left;
}

.start-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.search-result {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 20px;
}

.search-result .image {
  margin-right: 20px;
  width: 150px;
  height: 150px;
}
</style>
